package gupao.concurrency.demo.risk.calc;

import gupao.concurrency.demo.risk.calc.processor.CalcProcessor;
import gupao.concurrency.demo.risk.calc.processor.CalcThreadPoolService;
import gupao.concurrency.demo.risk.model.NodeTree;
import gupao.concurrency.demo.risk.model.NodeTreeMock;
import gupao.concurrency.demo.risk.model.ProcessDataModel;
import gupao.concurrency.demo.risk.model.RiskCapitalCalcContext;
import gupao.concurrency.demo.risk.scru.ScruResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class CalcService {

    @Resource(name = "optConcurrentCalcProcessor")
    private CalcProcessor calcProcessor;

    @Autowired
    private ProcessDataModel processDataModel;

    @Autowired
    private CalcThreadPoolService calcThreadPoolService;

    private volatile boolean stop = false;

    @PostConstruct
    public void start(){
        calcThreadPoolService.getCalcMainThreadPool().submit(() -> {
            log.info("Calculator service started.");
            while( !stop ){
                try {
                    log.info("retrive scru result from quque..");
                    ScruResult lastResult = processDataModel.getScruResultsQueue().poll(10, TimeUnit.SECONDS);
                    log.info("retrive scru result from quque..{}", (lastResult == null ? null : lastResult.getJob().getId()));
                    if(lastResult != null){
                        log.info("start to calc for job: {}", lastResult.getJob().getId());
                        NodeTree tree = NodeTreeMock.mockRiskJobTree();
                        RiskCapitalCalcContext context = new RiskCapitalCalcContext(tree, lastResult.getJob());
                        calcProcessor.calculateRiskCapital(context);
                    }
                } catch (Exception e) {
                    //省略：记录audit table 便于后续重试
                }
            }
        });


    }
}
